package com.hwadee.backend.controller;

import com.alibaba.fastjson2.JSONArray;
import com.hwadee.backend.util.DoubaoApiUtil;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import com.alibaba.fastjson2.JSONException;

@RestController
@RequestMapping("/doubao")
public class DoubaoController {
    @Autowired
    private DoubaoApiUtil doubaoApiUtil;

    @PostMapping("/chat")
    public String chat(@RequestBody String jsonStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            DoubaoApiUtil.ChatRequestBuilder builder = new DoubaoApiUtil.ChatRequestBuilder();
        
            if (jsonObject.containsKey("model")) {
                builder.setModel(jsonObject.getString("model"));
            }
            
            if (jsonObject.containsKey("messages")) {
                JSONArray messages = jsonObject.getJSONArray("messages");
                for (int i = 0; i < messages.size(); i++) {
                    JSONObject message = messages.getJSONObject(i);
                    builder.addMessage(message.getString("role"), message.getString("content"));
                }
            }
            
            if (jsonObject.containsKey("temperature")) {
                builder.setTemperature(jsonObject.getFloat("temperature"));
            }
            
            if (jsonObject.containsKey("top_p")) {
                builder.setTopP(jsonObject.getFloat("top_p"));
            }
            
            if (jsonObject.containsKey("max_tokens")) {
                builder.setMaxTokens(jsonObject.getIntValue("max_tokens"));
            }
            
            if (jsonObject.containsKey("stop")) {
                builder.setStop(jsonObject.get("stop"));
            }
            
            return doubaoApiUtil.chatWithDoubao(builder);
        } catch (JSONException e) {
            return "JSON 解析失败，请检查请求数据格式: " + e.getMessage();
        } catch (IOException e) {
            return "请求豆包 API 失败: " + e.getMessage();
        }
    }
}